<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-10-24
 * Time: 下午2:23
 */
namespace Home\Model;

use Think\Model;

class UserModel extends BaseModel{

    /**
     * 全部同步微信用户openid
     * @param string $next_openid 非必填
     * @return boolean
    */
    public function pullOpenid($next_openid = null){
        //设置超时时间
        set_time_limit( 1*60*60 );//一小时
        $res = self::$wechatObj->getUserList($next_openid);
        if(empty($res)){//接口调用失败
            return false;
        }
        $count = $res['count'];
        if(empty($count)) return true;
        $openidList = $res['data']['openid'];
        //获取当前本地的用户集合
        $localUsers = $this->field("openid,subscribe")->index('openid')->select();
        foreach ($openidList as $openid){
            //TODO 异常未处理，集合外数据关注状态更新未确认 add By lvxin
            if($localUsers[$openid]['openid'] == $openid){//本地存在
                if(empty($localUsers[$openid]['subscribe'])){//已取消状态，重新变为关注状态
                    $this->where("openid = '{$openid}'")->setField("subscribe",1);
                }
            }else{
                $this->add(array("openid"=>$openid,"subscribe"=>1));
            }
        }
        if($count > 10000){//微信请求数据单次10000，如为达到则说明本次查询已满
            return $this->pullUser($res['next_openid']);
        }
        return true;
    }
    /**
     * 同步微信用户信息
     * @param string $openid
     * @return array|boolean
     */
    public function pullWeixinUserInfo($openid){
        $userInfo = self::$wechatObj->getUserInfo($openid);
        if(empty($userInfo)) return false;
        $res = $this->where("openid = '{$userInfo['openid']}'")->save($userInfo);
        if($res === false){
            return false;
        }else{
            return $this->where("openid = '{$userInfo['openid']}'")->find();
        }
    }
    /**
     * 获取本地用户信息
     * @param string $openid
     * @return array|boolean
    */
    public function getLocalUserInfo($openid){

    }
    /**
     * 同步指定微信用户信息
     * @param array $openids
     * @return boolean
    */
    public function pullWeixinUser($openids){

    }
    /**
     * 获取本地用户数
    */
    public function getLocalUserCount(){
        return $this->where("subscribe = 1")->count();
    }

} 